import { unitWidth, halfUnitWidth, timeScaleHeight, barHeight, barMargin, hachureLines, isHoliday, createFlagGroup, syncLocal } from './initialization.js';

/**
 * 绘制时间轴背景
 * @param {Object} zr ZRender实例
 * @param {Object} chartState 图表状态对象
 */
export function drawTimeScaleBackground(zr, chartState) {
  const timeScale = new zrender.Rect({
    shape: {
      x: chartState.chartStartX + chartState.lastScrollX,
      y: chartState.chartStartY - timeScaleHeight,
      width: chartState.timeScaleWidth * unitWidth,
      height: timeScaleHeight
    },
    style: {
      fill: "rgba(255, 0,0, .2)"
    }
  });
  zr.add(timeScale);
}

/**
 * 绘制垂直网格线
 * @param {Object} zr ZRender实例
 * @param {Object} chartState 图表状态对象
 * @param {Array} tasks 任务数组
 * @param {Array} mileStones 里程碑数组
 * @param {Function} redrawChart 重绘图表函数
 */
export function drawVerticalGridLines(zr, chartState, tasks, mileStones, redrawChart) {
  const gridStartX = chartState.chartStartX;
  const gridEndX = chartState.timeScaleWidth * unitWidth;
  const gridLineCount = chartState.timeScaleWidth + 1;
  const deltaScrollX = Math.floor(chartState.lastScrollX / unitWidth);
  const viewPortTaskLength = Math.min(tasks.length, (chartState.canvasHeight - chartState.chartStartY) / (barHeight + barMargin));

  for (let i = 0 + deltaScrollX, count = 0; count < gridLineCount; i++, count++) {
    const gridX = gridStartX + i * unitWidth;
    
    // 绘制网格线
    const gridLine = new zrender.Line({
      shape: {
        x1: gridX,
        y1: chartState.chartStartY - timeScaleHeight,
        x2: gridX,
        y2: chartState.chartStartY + (barHeight + barMargin) * viewPortTaskLength
      },
      style: {
        stroke: "lightgray"
      }
    });

    // 绘制日期文字和休息日斜线
    if (count < gridLineCount - 1) {
      drawDateText(zr, i, gridX, chartState, mileStones, redrawChart);
      drawHolidayHachure(zr, i, chartState, viewPortTaskLength);
    }
    
    zr.add(gridLine);
  }
}

/**
 * 绘制日期文字
 * @param {Object} zr ZRender实例
 * @param {number} i 日期索引
 * @param {number} gridX 网格X坐标
 * @param {Object} chartState 图表状态对象
 * @param {Array} mileStones 里程碑数组
 * @param {Function} redrawChart 重绘图表函数
 */
function drawDateText(zr, i, gridX, chartState, mileStones, redrawChart) {
  const now = +new Date('2024-01-01');
  const currentDate = now + i * 60 * 1000 * 60 * 24;
  const dateInfo = isHoliday(currentDate);

  const dateText = new zrender.Text({
    style: {
      text: dateInfo.dateString,
      x: gridX,
      y: chartState.chartStartY - timeScaleHeight,
    },
    z: 1
  });

  // 创建标志组
  const [flagGroup, { flag }] = createFlagGroup(zr, gridX, halfUnitWidth, chartState.chartStartY, timeScaleHeight);

  // 点击事件处理
  dateText.on('click', function () {
    const index = mileStones.findIndex(item => item.start === i);
    if (index === -1) {
      if (confirm('Do you want to CREATE a milestone here?')) {
        const mileStoneName = prompt('mileStone name?');
        mileStones.push({
          start: i,
          name: mileStoneName
        });
        syncLocal();
      }
    } else {
      if (confirm('Do you want to DELETE the milestone here?')) {
        mileStones.splice(index, 1);
        syncLocal();
      }
    }
    redrawChart(true);
  });

  // 鼠标悬停事件
  dateText.on('mouseover', function (e) {
    this.attr({
      style: {
        opacity: 0
      }
    });
    flagGroup.show();
  });

  dateText.on('mouseout', function (e) {
    this.attr({
      style: {
        opacity: 1
      }
    });
    flagGroup.hide();
  });

  // 调整文字位置
  const { width, height } = dateText.getBoundingRect();
  dateText.attr({
    style: {
      x: gridX - width / 2 + halfUnitWidth,
      y: chartState.chartStartY - timeScaleHeight - height / 2 + timeScaleHeight / 2,
    }
  });

  zr.add(dateText);
}

/**
 * 绘制休息日斜线
 * @param {Object} zr ZRender实例
 * @param {number} i 日期索引
 * @param {Object} chartState 图表状态对象
 * @param {number} viewPortTaskLength 视口任务长度
 */
function drawHolidayHachure(zr, i, chartState, viewPortTaskLength) {
  const now = +new Date('2024-01-01');
  const currentDate = now + i * 60 * 1000 * 60 * 24;
  const dateInfo = isHoliday(currentDate);

  if (dateInfo.isHoliday) {
    try {
      const lines = hachureLines([
        [chartState.chartStartX + i * unitWidth, chartState.chartStartY],
        [chartState.chartStartX + i * unitWidth + unitWidth, chartState.chartStartY],
        [chartState.chartStartX + i * unitWidth + unitWidth, chartState.chartStartY + (barHeight + barMargin) * viewPortTaskLength],
        [chartState.chartStartX + i * unitWidth, chartState.chartStartY + (barHeight + barMargin) * viewPortTaskLength]
      ], 10, 45);

      lines.forEach(line => {
        const [x1, y1] = line[0];
        const [x2, y2] = line[1];
        const l = new zrender.Line({
          shape: {
            x1, y1, x2, y2
          },
          style: {
            stroke: 'rgba(221, 221, 221, 0.7)'
          }
        });
        zr.add(l);
      });
    } catch (error) {
      // 静默处理错误
    }
  }
}

/**
 * 绘制水平网格线
 * @param {Object} zr ZRender实例
 * @param {Object} chartState 图表状态对象
 */
export function drawHorizontalGridLines(zr, chartState) {
  const gridEndX = chartState.timeScaleWidth * unitWidth;

  for (let j = 0; j < 1; j++) {
    const gridY = chartState.chartStartY + j * (barHeight + barMargin);
    const gridLineY = new zrender.Line({
      shape: {
        x1: chartState.chartStartX,
        y1: gridY,
        x2: gridEndX + chartState.chartStartX,
        y2: gridY
      },
      style: {
        stroke: "lightgray"
      }
    });
    zr.add(gridLineY);
  }
} 